package com.narata.netty.multiThread;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.LinkedBlockingDeque;

import static com.narata.netty.util.BufferUtil.print;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 23:31 2022-04-24
 * @Modified By:
 **/
public class Worker implements Runnable {

    private Thread thread;

    private Selector selector;
    private String name;
    private volatile boolean start = false;
    private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque<>();

    public Worker(String name) {
        this.name = name;
    }

    // 初始化线程和selector
    public void register(SocketChannel sc) throws IOException {
        // TODO 线程不安全
        if (!start) {
            start = true;
            selector = Selector.open();
            thread = new Thread(this, name);
            thread.start();
        }
        queue.add(() -> {
            try {
                sc.register(selector, SelectionKey.OP_READ,  null);
            } catch (ClosedChannelException e) {
                e.printStackTrace();
            }
        });
        selector.wakeup();
    }

    @Override
    public void run() {
        while (true) {
            try {
                selector.select();
                Runnable poll = queue.poll();
                if (poll != null) {
                    poll.run();
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();

                    if (key.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.read(buffer);
                        buffer.flip();
                        System.out.println(Thread.currentThread().getName());

                        print(buffer);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public Selector getSelector() {
        return selector;
    }
}
